package com.dm.cloud.utils.http;

import com.alibaba.druid.support.json.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;


@Slf4j
public class HttpUtils {

    /**
     * GET请求
     * @param url
     * @return
     */
    public static Response doGet(String url) throws Exception {
        Request request = new Request.Builder().url(url).get().build();
        return httpDo(request);
    }

    /**
     * POST请求
     * @param url
     * @return
     */
    public static Response doPost(String url, Map<String,Object> dataOrigin) throws Exception {
        //创建Request
        FormBody.Builder requestBuilder = new FormBody.Builder();

        dataOrigin.entrySet().stream().forEach(e->requestBuilder.add(e.getKey(), JSONUtils.toJSONString(e.getValue())));

        Request request = new Request.Builder().url(url).post(requestBuilder.build()).build();
        return httpDo(request);
    }

    //请求操作
    private static Response httpDo(Request request) throws Exception {
        final Response[] resultRespone = {null};
        final IOException[] exception = {null};

        OkHttpClient mOkHttpClient = new OkHttpClient();
        //3，创建call对象并将请求对象添加到调度中

        Call call = mOkHttpClient.newCall(request);
        //同步
        Response response = call.execute();

        return response;
    }

}
